package com.yztstudy.Controller;

import com.yztstudy.Entity.Food;
import com.yztstudy.Entity.FoodType;
import com.yztstudy.Service.FoodService;
import com.yztstudy.Service.FoodTypeService;
import com.yztstudy.Utils.FileFunctionUtils;
import com.yztstudy.Utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Food的表示层
 */

@Controller
@Scope("prototype") //spring注解的bean可以变成多例
public class FoodController {

    //设置真实的保存图片文件的路径
    private static final String realPath = "D:\\JavaFramework\\P1_点餐系统\\P1_Restaurant\\src\\main\\resources\\public\\upload";
    //设置运行路径
    private static final String runPath = "D:\\JavaFramework\\P1_点餐系统\\P1_Restaurant\\target\\classes\\public\\upload";


    @Autowired
    private FoodService foodService;

    @Autowired
    private FoodTypeService foodTypeService;

    /**
     * 展示第一页的分页
     */
    @RequestMapping("/foodQueryList/{currentPage}/{pageSize}")
    public String foodQueryList(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize, ModelMap modelMap)
    {
        //1.添加分页条件
        Map<String, Object> map = new HashMap<>();
        map.put("currentPage", (currentPage - 1) * pageSize);
        map.put("pageSize", pageSize);

        //2.查询
        List<Food> foods = foodService.getFoods(map); //分页查询的结果
        int totalCount = foodService.totalCount(""); //总记录数

        //3.分页
        PageUtils<Food> pageUtils = new PageUtils<>(pageSize, currentPage, totalCount, foods);
        modelMap.addAttribute("pageUtils", pageUtils);

        //4.跳转
        return "foodList";
    }

    /**
     * 上一页,下一页,首页和尾页
     */
    @PostMapping("/newPage/{currentPage}/{pageSize}")
    public String nextPage(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize, String keyword, ModelMap modelMap)
    {
        //1.添加分页条件
        Map<String, Object> map = new HashMap<>();
        map.put("currentPage", (currentPage - 1) * pageSize);
        map.put("pageSize", pageSize);
        map.put("title", keyword);

        //2.查询
        List<Food> foods = foodService.getFoods(map); //分页查询的结果
        int totalCount = foodService.totalCount(keyword); //总记录数

        //3.分页
        PageUtils<Food> pageUtils = new PageUtils<>(pageSize, currentPage, totalCount, foods);
        modelMap.addAttribute("pageUtils", pageUtils);
        modelMap.addAttribute("keyword", keyword);

        //4.跳转
        return "foodList";
    }

    /**
     * 获取所有的可用菜系
     */
    @ResponseBody
    @GetMapping("/getAllFoodTypes")
    public List<FoodType> findAllFoodTypes()
    {
        return foodTypeService.getAllFoodType();
    }

    /**
     * 新增菜品,带文件上传
     */
    @PostMapping("/foodAdd")
    public void addFood(Food food, @RequestParam("imageUrl") MultipartFile file, HttpServletResponse response) throws IOException
    {
        //字符过滤
        response.setContentType("text/html;charset=utf-8");

        //如果没有接到文件
        if (file.isEmpty())
        {
            response.getWriter().write("<script>alert('菜品图片不能为空!'); location.href = '/page_saveFood';</script>");
            return;
        }

        //文件名
        String fileName = file.getOriginalFilename();
        //后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        //最后保存的文件
        fileName = UUID.randomUUID() + suffixName;

        File f1 = new File(realPath, fileName);
        File f2 = new File(runPath, fileName);

        //检测是否存在该目录
        if (!f1.getParentFile().exists())
        {
            //不存在就创建这个目录
            f1.getParentFile().mkdirs();
        }

        //设置菜品的文件名
        food.setPhoto(fileName);
        //添加菜品
        int count = 0;
        try {
            count = foodService.addFood(food);
        }catch (Exception e)
        {
            response.getWriter().write("<script>alert('菜品添加失败!'); location.href = '/page_saveFood';</script>");
        }finally {
            if (count > 0)
            {
                //保存文件
                file.transferTo(f1);
                FileFunctionUtils.copyFile(f1, f2);
                response.getWriter().write("<script>alert('菜品添加成功!'); location.href = '/foodQueryList/1/8';</script>");
            }else {
                response.getWriter().write("<script>alert('菜品添加失败!'); location.href = '/page_saveFood';</script>");
            }
        }
    }

    /**
     * 跳转页面
     */
    @GetMapping("/toUpdateFood/{id}")
    public String toUpdateFood(@PathVariable("id") Integer id, ModelMap map)
    {
        //1.获取对象
        Food food = foodService.getFoodById(id);
        //2.请求转发
        map.addAttribute("food", food);
        return "updateFood";
    }

    /**
     * 更新菜品
     */
    @PostMapping("/foodUpdate")
    public void updateFood(Food food, @RequestParam("imageUrl") MultipartFile file, HttpServletResponse response) throws IOException
    {
        //字符过滤
        response.setContentType("text/html;charset=utf-8");

        //定义文件名
        String fileName = null;
        String suffixName = null; //后缀名

        //如果没有接收到新的文件
        if (file.isEmpty())
        {
            fileName = food.getPhoto();

            //设置菜品的文件名
            food.setPhoto(fileName);
            //添加菜品
            int count = 0;
            try {
                count = foodService.updateFood(food);
            }catch (Exception e)
            {
                response.getWriter().write("<script>alert('菜品修改失败!'); location.href = '/toUpdateFood/" + food.getId() + "';</script>");
            }finally {
                if (count > 0)
                {
                    response.getWriter().write("<script>alert('菜品修改成功!'); location.href = '/foodQueryList/1/8';</script>");
                }else {
                    response.getWriter().write("<script>alert('菜品修改失败!'); location.href = '/toUpdateFood/" + food.getId() + "';</script>");
                }
            }
        }else {
            //如果接收到了新的文件
            fileName = file.getOriginalFilename();
            suffixName = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffixName;

            //保存最后的文件
            File f1 = new File(realPath, fileName);
            File f2 = new File(runPath, fileName);

            //检测是否存在该目录
            if (!f1.getParentFile().exists())
            {
                //不存在就创建这个目录
                f1.getParentFile().mkdirs();
            }

            //设置菜品的文件名
            food.setPhoto(fileName);
            //添加菜品
            int count = 0;
            try {
                count = foodService.updateFood(food);
            }catch (Exception e)
            {
                response.getWriter().write("<script>alert('菜品修改失败!'); location.href = '/toUpdateFood/" + food.getId() + "';</script>");
            }finally {
                if (count > 0)
                {
                    //保存文件
                    file.transferTo(f1);
                    FileFunctionUtils.copyFile(f1, f2);
                    response.getWriter().write("<script>alert('菜品修改成功!'); location.href = '/foodQueryList/1/8';</script>");
                }else {
                    response.getWriter().write("<script>alert('菜品修改失败!'); location.href = '/toUpdateFood/" + food.getId() + "';</script>");
                }
            }
        }
    }

    /**
     * 删除菜品
     */
    @GetMapping("/foodDelete/{id}")
    public void foodDelete(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException
    {
        //字符过滤
        response.setContentType("text/html;charset=utf-8");

        int result = -1;
        try {
            result = foodService.deleteFood(id);
        }catch (Exception e)
        {
            response.getWriter().write("<script>alert('删除菜品失败!'); location.href = '/foodQueryList/1/8';</script>");
        }finally {
            if (result > 0)
            {
                response.getWriter().write("<script>alert('删除菜品成功!'); location.href = '/foodQueryList/1/8';</script>");
            }else {
                response.getWriter().write("<script>alert('删除菜品失败!'); location.href = '/foodQueryList/1/8';</script>");
            }
        }
    }

    /**
     * 激活菜品
     */
    @GetMapping("/foodActive/{id}")
    public void foodActive(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException
    {
        //字符过滤
        response.setContentType("text/html;charset=utf-8");

        int result = -1;
        try {
            result = foodService.activeFood(id);
        }catch (Exception e)
        {
            response.getWriter().write("<script>alert('激活菜品失败!'); location.href = '/foodQueryList/1/8';</script>");
        }finally {
            if (result > 0)
            {
                response.getWriter().write("<script>alert('激活菜品成功!'); location.href = '/foodQueryList/1/8';</script>");
            }else {
                response.getWriter().write("<script>alert('激活菜品失败!'); location.href = '/foodQueryList/1/8';</script>");
            }
        }
    }
}
